package com.weipt.syn;

import com.weipt.oper.Sleep2;

import java.util.concurrent.TimeUnit;

/**
 * @program: Learning
 * @description: 线程同步
 * @Company: 汇华(北京)信息咨询服务有限公司
 * @author: peter.wei
 * @create: 2020-07-28 15:02
 **/
public class syn1 {
    static class MyRunnable implements Runnable{
        private static int ticket = 20;
        @Override
        public void run() {
            while (true){
                if(!canBuy()){
                    break;
                }
            }
        }
        private synchronized boolean canBuy(){
            try {
                //使当前线程休眠1秒，休眠期间不会释放锁，其它线程不能访问。
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (ticket == 1) {
                --ticket;
                System.out.println(Thread.currentThread().getName() + ":售一张,票售完了");
                return false;
            } else if(ticket == 0){
                System.out.println(Thread.currentThread().getName() + ":票售完了");
                return false;
            }else {
                System.out.println(Thread.currentThread().getName() + ":售一张,票还剩:" + (--ticket) + "张");
                return true;
            }
        }
    }

    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread t = new Thread(myRunnable, "小明");
        Thread t2 = new Thread(myRunnable, "大黑");
        Thread t3 = new Thread(myRunnable, "张红");
        t.start();
        t2.start();
        t3.start();
    }
}